import {reactive} from "vue";
import {MenuItemType} from "../../starter/menu-manager";
import Asserts from "../../lang/core/asserts";
import router from "@/router/index";

export function useMenu(){

    /**
     * 历史点击，也就是选项卡
     */
    const menus_tabs: MenuItemType[] = reactive<MenuItemType[]>([]);

    /**
     * 上一次点击的菜单
     */
    let post_menu: MenuItemType = undefined;

    /**
     * 点击菜单
     *
     */
    const openPage = (item: MenuItemType) => {
        if (post_menu != null) {
            post_menu.active = false;
        }
        item.active = true;
        post_menu = item;

        router.push({path: item.path});

        if (!menus_tabs.includes(item)) {
            menus_tabs.push(item);
        }
    }

    /**
     * 从选项卡移除一个菜单
     * @param idx
     */
    const removeTab = (idx) => {
        Asserts.isTrue(idx < menus_tabs.length, 'out of bounds of array')
        const menu = menus_tabs[idx];

        // open first tab
        if(menu.active && menus_tabs.length > 1){
            openPage(menus_tabs[0]);
        }

        // remove tab
        menus_tabs.splice(idx, 1);
    }

    /**
     * 打开主页
     */
    const homePage = () => {
        router.push({path: "/"});
    }

    return {menus_tabs, openPage, removeTab, homePage}
}